// CLC Dandelion - A Web-based Daisy Player
//by Charles L. Chen
 
//This program is free software; you can redistribute it
//and/or modify it under the terms of the GNU General Public
//License as published by the Free Software Foundation;
//either version 2.1 of the License, or (at your option) any
//later version.  This program is distributed in the hope
//that it will be useful, but WITHOUT ANY WARRANTY; without
//even the implied warranty of MERCHANTABILITY or FITNESS FOR
//A PARTICULAR PURPOSE. See the GNU General Public License for
//more details.  You should have received a copy of the GNU
//General Public License along with this program; if not, look
//on the web at on the web at http://www.gnu.org/copyleft/gpl.html
//or write to the Free Software Foundation, Inc., 59 Temple Place,
//Suite 330, Boston, MA 02111-1307, USA.
 
//Last Modified Date 05/11/2008

//------------------------------------------

var clcd = function(contentFrame){
  this.contentFrame = contentFrame;
  
  this.masterSmil = null;
  this.smilUrlArray = new Array();
  this.smilTitlesArray = new Array();
  this.smilUrlIndex = -1;
  
  this.currentSmil = null;
  this.parsArray = new Array();
  this.parsIndex = -1;
  
  this.currentNode = null;
  this.origBackgroundColor = null;
  
  this.audioQueue = new Array();
  this.audioIndex = -1;
  
  this.sound = new AxsSound(false);

  this.sound.setVerbosity('minimal');
  this.sound.init();
  
  this.busy = false;
  this.shouldStop = false;
  
  //Detect the browser
  this.browser = 'ff';
  var agt=navigator.userAgent.toLowerCase();
  if ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1)){
    this.browser = 'ie';
  }
};

clcd.prototype.createHTTPReqObj = function(){
  var req = null;
  if (this.browser == 'ff'){
    req = new XMLHttpRequest();
    req.overrideMimeType('text/xml');
  } else {
    req = new ActiveXObject("MSXML2.XMLHTTP");
  }
  return req;
};

clcd.prototype.xmlObjFromHTTPReq = function(req){
  var xmlObj = null;
  if (this.browser == 'ff'){
    var xmlObj = req.responseXML;
  } else {
    xmlObj = new ActiveXObject("Microsoft.XMLDOM");
    xmlObj.loadXML(req.responseText);
  }
  return xmlObj;  
};

clcd.prototype.loadMaster = function(masterURL){
  var req = null; 
  var self = this;  
  
  req = this.createHTTPReqObj();
  req.open('GET', masterURL, true);
  req.onreadystatechange = function(){
                 if (req.readyState==4) {
                   self.masterSmil = self.xmlObjFromHTTPReq(req);
 	   		       var refs = self.masterSmil.getElementsByTagName('ref');
				   for (var i = 0, ref; ref = refs[i]; i++){
                     self.smilUrlArray.push(ref.getAttribute('src'));
				     self.smilTitlesArray.push(ref.getAttribute('title'));
                   }		
                   self.smilUrlIndex = -1;	
                   self.loadNextSmil(false);	
                 }				 
               };
  			   
  req.send(null);
};

clcd.prototype.loadNextSmil = function(autoStartBool){
  this.smilUrlIndex++;
  if (this.smilUrlIndex < this.smilUrlArray.length){
    var req = this.createHTTPReqObj();
    var self = this;
    req.open('GET', this.smilUrlArray[this.smilUrlIndex], true);
    req.onreadystatechange = function(){
                   if (req.readyState==4) {
                     self.currentSmil = self.xmlObjFromHTTPReq(req);	
				     var pars = self.currentSmil.getElementsByTagName('par');
				     self.parsArray = new Array();
                     for (var i = 0, par; par = pars[i]; i++){
                       self.parsArray.push(par);
                     }		
                     self.parsIndex = -1;	
	 			     if (autoStartBool){
 				       self.loadNextPar();
				     } else {
				       if (!self.contentFrame.src){
					     var par = self.parsArray[0];
	                     var text = par.getElementsByTagName('text')[0];
					     self.contentFrame.src = text.getAttribute('src');
					   }
                     }
                   }					 
                 };
    req.send(null);	
  } else {
    this.smilUrlIndex = 0;
  }
};

clcd.prototype.loadPrevSmil = function(autoStartBool){
  this.smilUrlIndex--;
  if (this.smilUrlIndex >= 0){
    var req = this.createHTTPReqObj();
    var self = this;
    req.open('GET', this.smilUrlArray[this.smilUrlIndex], true);
    req.onreadystatechange = function(){
                   if (req.readyState==4) {
                     self.currentSmil = self.xmlObjFromHTTPReq(req);		
				     var pars = self.currentSmil.getElementsByTagName('par');
				     self.parsArray = new Array();
                     for (var i = 0, par; par = pars[i]; i++){
                       self.parsArray.push(par);
                     }		
                     self.parsIndex = self.parsArray.length;	
				     if (autoStartBool){
				       self.loadPrevPar();
				     } else {
				       if (!self.contentFrame.src){
					     var par = self.parsArray[0];
	                     var text = par.getElementsByTagName('text')[0];
					     self.contentFrame.src = text.getAttribute('src');
					   }
                     }				   
                   }					 
                 };
    req.send(null);	
  } else {
   this.smilUrlIndex = this.smilUrlArray.length;
  }
};

clcd.prototype.loadNextPar = function(){
  this.parsIndex++;
  if (this.parsIndex < this.parsArray.length){
    var par = this.parsArray[this.parsIndex];
	var text = par.getElementsByTagName('text')[0];
	var self = this;
	
	var oldBaseUrl = this.contentFrame.src.toString().split('#')[0];
	var newBaseUrl = text.getAttribute('src').toString().split('#')[0];
	
	if (oldBaseUrl.indexOf(newBaseUrl) == -1){
	  this.contentFrame.src = text.getAttribute('src');
	  this.contentFrame.onload = function(){ self.processLoadedFrame(self) };
	} else {
	  this.contentFrame.src = text.getAttribute('src');
	  self.processLoadedFrame(self);
	}
  } else {
    this.loadNextSmil(true);
  } 
};

clcd.prototype.loadPrevPar = function(){
  this.parsIndex--;
  if (this.parsIndex >= 0){
    var par = this.parsArray[this.parsIndex];
	var text = par.getElementsByTagName('text')[0];
	var self = this;
	
	var oldBaseUrl = this.contentFrame.src.toString().split('#')[0];
	var newBaseUrl = text.getAttribute('src').toString().split('#')[0];
	
	if (oldBaseUrl.indexOf(newBaseUrl) == -1){
	  this.contentFrame.src = text.getAttribute('src');
	  this.contentFrame.onload = function(){ self.processLoadedFrame(self) };
	} else {
	  this.contentFrame.src = text.getAttribute('src');
	  self.processLoadedFrame(self);
	}
  } else {
    this.loadPrevSmil(true);
  }
};

clcd.prototype.processLoadedFrame = function(self){
  if (this.currentNode){
    this.currentNode.style.backgroundColor = this.origBackgroundColor;
  }  
  var par = self.parsArray[self.parsIndex];
  var text = par.getElementsByTagName('text')[0];
  var src = text.getAttribute('src');
  if (src.indexOf('#') != -1){
    var id = src.substring(src.indexOf('#')+1);
	var contentDoc = null;
	if (this.browser == 'ff'){
	  contentDoc = self.contentFrame.contentDocument;
	} else {
	  contentDoc = self.contentFrame.contentWindow.document;
	}
    this.currentNode = contentDoc.getElementById(id);
    this.origBackgroundColor = this.currentNode.style.backgroundColor;	
	this.currentNode.style.backgroundColor = '#FFFF00';
    this.playCurrentParAudio(self);
  }
};

clcd.prototype.playCurrentParAudio = function(self){
  var par = self.parsArray[self.parsIndex];
  var audioNodes = par.getElementsByTagName('audio');
  self.audioQueue = new Array();
  self.audioIndex = -1;
  for (var i=0,audio; audio = audioNodes[i]; i++){
    var audioObj = new Object();
    var src = audio.getAttribute('src');
    var baseURL = null;
    if (src.indexOf('http://') !== 0){
	  if (self.browser == 'ff'){
        baseURL = audio.baseURI.substring(0,audio.baseURI.lastIndexOf('/')+1);
	  } else {
	  	var loc = document.location.toString();
	    baseURL = loc.substring(0,loc.lastIndexOf('/')+1);
	  }
    }	
	audioObj.src = baseURL + src;
	var beginStr = audio.getAttribute('clip-begin');
	var str = '';
	var j = 0;
	var char = '';
	for (j=0; char = beginStr.charAt(j); j++){
      if ((char >= '0') && (char <= '9'))
      str = str + char;
    }	
	audioObj.begin = parseInt(str);
	var endStr = audio.getAttribute('clip-end');
	str = '';
	j = 0;
	char = '';
	for (j=0; char = endStr.charAt(j); j++){
      if ((char >= '0') && (char <= '9'))
      str = str + char;
    }	
	audioObj.end = parseInt(str);
	self.audioQueue.push(audioObj);
  }  
  self.sound.stop();
  self.busy = true;
  self.processAudioQueue(self);
};

clcd.prototype.processAudioQueue = function(self){
  if (self.sound.isPlaying()){
    window.setTimeout(function(){self.processAudioQueue(self)},100);
    return;
  }
  self.audioIndex++;
  if (self.audioIndex < self.audioQueue.length){
    var audio = self.audioQueue[self.audioIndex];
    self.sound.playSeg(audio.src,audio.begin,audio.end);
    window.setTimeout(function(){self.processAudioQueue(self)},100);
	return;
  }
  self.busy = false;
};

clcd.prototype.run = function(){
  if (this.shouldStop){
    return;
  }
  var self = this;
  if (!self.busy){
    self.loadNextPar();
  }
  window.setTimeout(function(){self.run()},1000);
};

clcd.prototype.stop = function(){
  this.shouldStop = true;
  this.audioQueue = new Array();
  this.audioIndex = -1;
  this.sound.stop();
  this.busy = false;
};

clcd.prototype.play = function(){
  this.shouldStop = false;
  this.run();
};